package com.smartodo.web.servlets;


import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.owasp.esapi.ESAPI;

import com.smartodo.utils.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;


/**
 * @author Pawan Singh
 * Servlet implementation class for Servlet: Home
 *
 */
 public class StodoActions extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public StodoActions() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doPost(request, response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{

		if(request.getParameter("service") != null)
		{
			if(request.getParameter("service").equals("addtask"))
			{
				performAddTask(request, response);
			}
			if(request.getParameter("service").equals("gettask"))
			{
				performGetTask(request, response);
			}
			if(request.getParameter("service").equals("updatetask"))
			{
				performUpdateTask(request, response);
			}
			if(request.getParameter("service").equals("deletetask"))
			{
				performDeleteTask(request, response);
			}
			
		}
	}
	private void performGetTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		int taskid = 0;
		PrintWriter out = response.getWriter();
		try
		{
			if(request.getParameter("taskid") == null)
				throw new Exception("");

			taskid = Integer.parseInt(request.getParameter("taskid"));
			STask t = DbUtils.getTaskById(taskid);
			if(t == null)
				throw new Exception("");
			
			out.print("<xml>");
			out.print("<message><taskid>" + t.taskid + "</taskid>");
			out.print("<taskname>" + t.task_name + "</taskname>");
			out.print("<taskdate>" + t.getDateStr() + "</taskdate>");
			out.print("<priority>" + t.priority + "</priority>");
			out.print("</message></xml>");
		}
		catch(Exception e)
		{ 
			out.print("<xml><message><error>Unable to find this task</error></message></xml>");
		}
		out.close();
		return;
	}
	
	private void performAddTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// Initialize:
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTimeZone(TimeZone.getTimeZone("US/Central"));
		
		// selected date
		int day = 0, month = 0 , year =0;
		String taskname = "";
		String priority = "";
		boolean error = false;
		
		// get the parameters from request when selected from the select box
		if(request.getParameter("date") != null)
		{
			try
			{
				String inputDate = request.getParameter("date");
				SimpleDateFormat sdf_task = new SimpleDateFormat("MM/dd/yyyy");
				java.util.Date iDate = sdf_task.parse(inputDate);
				
				cal.setTime(iDate);
				day = cal.get(Calendar.DAY_OF_MONTH);
				month = cal.get(Calendar.MONTH);
				year = cal.get(Calendar.YEAR);
				
				GregorianCalendar todays_cal = new GregorianCalendar();
				todays_cal.setTimeZone(TimeZone.getTimeZone("US/Central"));
				
				int todays_day = todays_cal.get(Calendar.DAY_OF_MONTH);
				int todays_month = todays_cal.get(Calendar.MONTH);
				int todays_year = todays_cal.get(Calendar.YEAR);

				if(todays_year != year || todays_month != month || todays_day != day)
				{
					if(cal.compareTo(todays_cal) < 0)
					{
						PrintWriter out = response.getWriter();
						out.print("<xml><message><error>Unable to add task before current date</error></message></xml>");
						out.close();
						return;
					}
				}
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		if(request.getParameter("taskname") != null && !error)
		{
			try
			{
				taskname = request.getParameter("taskname");
				if(!ESAPI.validator().isValidInput("Task Name", taskname, "TaskName", 255, false))
				{
					error=true;
                }
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		if(request.getParameter("priority") != null && !error)
		{
			try
			{
				priority = request.getParameter("priority");
				if(!priority.equals("h") && !priority.equals("m") && !priority.equals("l"))
					error = true;
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		
		if(error)
		{
			PrintWriter out = response.getWriter();
			out.print("<xml><message><error>Error: Invalid Input.</error></message></xml>");
			out.close();
			return;
		}
		cal.set(year, month, day);
		//session.setAttribute("selectedDate", cal);
		try
		{
			HttpSession session = request.getSession();
			String loginId = session.getAttribute("loginId").toString();
			DbUtils.InsertTodoData(loginId, taskname, priority, day, month, year);
		}
		catch(Exception ex)
		{
			PrintWriter out = response.getWriter();
			out.print("<xml><message><error>Error inserting the task</error></message></xml>");
			out.close();
			return;
		}

	}   
	
	
	private void performUpdateTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// Initialize:
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTimeZone(TimeZone.getTimeZone("US/Central"));
		
		// selected date
		int day = 0, month = 0 , year =0;
		int taskid = 0;
		String taskname = "";
		String priority = "";
		boolean error = false;
		
		// get the parameters from request
		if(request.getParameter("taskid") != null && !error)
		{
			try
			{
				taskid = Integer.parseInt(request.getParameter("taskid"));
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		
		if(request.getParameter("date") != null && !error)
		{
			try
			{
				String inputDate = request.getParameter("date");
				SimpleDateFormat sdf_task = new SimpleDateFormat("MM/dd/yyyy");
				java.util.Date iDate = sdf_task.parse(inputDate);
				
				cal.setTime(iDate);
				day = cal.get(Calendar.DAY_OF_MONTH);
				month = cal.get(Calendar.MONTH);
				year = cal.get(Calendar.YEAR);
				
				GregorianCalendar todays_cal = new GregorianCalendar();
				todays_cal.setTimeZone(TimeZone.getTimeZone("US/Central"));
				
				int todays_day = todays_cal.get(Calendar.DAY_OF_MONTH);
				int todays_month = todays_cal.get(Calendar.MONTH);
				int todays_year = todays_cal.get(Calendar.YEAR);

				if(todays_year != year || todays_month != month || todays_day != day)
				{
					if(cal.compareTo(todays_cal) < 0)
					{
						PrintWriter out = response.getWriter();
						out.print("<xml><message><error>Unable to update task before current date</error></message></xml>");
						out.close();
						return;
					}
				}
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		if(request.getParameter("taskname") != null && !error)
		{
			try
			{
				taskname = request.getParameter("taskname");
				if(!ESAPI.validator().isValidInput("Task Name", taskname, "TaskName", 255, false))
				{
					error=true;
                }
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		if(request.getParameter("priority") != null && !error)
		{
			try
			{
				priority = request.getParameter("priority");
				if(!priority.equals("h") && !priority.equals("m") && !priority.equals("l"))
					error = true;

			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		
		if(error)
		{
			PrintWriter out = response.getWriter();
			out.print("<xml><message><error>Error: Invalid Input.</error></message></xml>");
			out.close();
			return;
		}
		//cal.set(year, month, day);
		//session.setAttribute("selectedDate", cal);
		try
		{
			HttpSession session = request.getSession();
			String loginId = session.getAttribute("loginId").toString();

			DbUtils.UpdateTodoData(loginId, taskid, taskname, priority, day, month, year);
		}
		catch(Exception ex)
		{
			PrintWriter out = response.getWriter();
			out.print("<xml><message><error>Error updating the task</error></message></xml>");
			out.close();
			return;
		}
	}
	
	private void performDeleteTask(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// Initialize:
		GregorianCalendar cal = new GregorianCalendar();
		cal.setTimeZone(TimeZone.getTimeZone("US/Central"));
		
		int taskid = 0;
		boolean error = false;
		
		// get the parameters from request
		if(request.getParameter("taskid") != null && !error)
		{
			try
			{
				taskid = Integer.parseInt(request.getParameter("taskid"));
			}
			catch(Exception e){ error = true;}
		}
		else{error = true;}

		if(error)
		{
			PrintWriter out = response.getWriter();
			out.print("<xml><message><error>Error deleting the task</error></message></xml>");
			out.close();
			return;
		}
		
		try
		{
			HttpSession session = request.getSession();
			String loginId = session.getAttribute("loginId").toString();

			DbUtils.DeleteTodoData(loginId, taskid);
		}
		catch(Exception ex)
		{
			PrintWriter out = response.getWriter();
			out.print("<xml><message><error>Error deleting the task</error></message></xml>");
			out.close();
			return;
		}
	}
}